package com.lujieni.springbootjvm.service;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 使用cglib当setUseCache为false的时候可能会造成metaspace溢出的问题
 */
public class CglibService {

    public static void main(String[] args) {

        Integer a = 1000;
        Integer b = 1000;
        System.out.println(a == b); // false


        OpenCoder openCoder = getOpenCoder();
        OpenCoder openCoder2 = getOpenCoder();
        System.out.println(openCoder == openCoder2);
        System.out.println(openCoder.getClass().getName());
        System.out.println(openCoder2.getClass().getName());
    }



    private static OpenCoder getOpenCoder() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(OpenCoder.class);
        enhancer.setUseCache(false); //为false的话生成的代理类每一个都是一个新类,因此会出现metaspace溢出
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if(method.getName().equals("study")){
                    System.out.println("关注OpenCoder公众号");
                    return methodProxy.invokeSuper(o, objects);
                }else{
                    return methodProxy.invokeSuper(o, objects);
                }
            }
        });

        OpenCoder openCoder = (OpenCoder) enhancer.create();
        System.out.println(openCoder.getClass().getName());
        openCoder.study();
        return  openCoder;
    }


}



class OpenCoder{
    public void study(){
        System.out.println("study......");
    }
}